<template>
  <div class="flex items-center justify-between">
    <p class="font-semibold">问题</p>
    <div>
      <button
        class="inline-flex items-center h-8 px-3 text-sm transition rounded-sm bg-secondary highlight-white/5 text-secondary-foreground hover:bg-secondary/80"
        :disabled="loading"
        title="fadfasdf"
        @click="reportMessageHandle"
      >
        <Shell
          v-if="loading"
          class="w-3.5 h-3.5 mr-1 -ml-1"
          :class="{ 'animate-spin': loading }"
        />
        <Send v-else class="w-3.5 h-3.5 mr-1 -ml-1" /> 上报
      </button>
      <button
        class="inline-flex items-center h-8 px-3 mx-1 text-sm transition rounded-sm bg-secondary highlight-white/5 text-secondary-foreground hover:bg-secondary/80"
        :disabled="loading"
        @click="askMessageHandle"
      >
        <Shell
          v-if="loading"
          class="w-3.5 h-3.5 mr-1 -ml-1"
          :class="{ 'animate-spin': loading }"
        />
        <Send v-else class="w-3.5 h-3.5 mr-1 -ml-1" /> 提问
      </button>
      <button
        class="inline-flex items-center h-8 px-3 mx-1 text-sm transition rounded-sm bg-secondary highlight-white/5 text-secondary-foreground hover:bg-secondary/80"
        @click="clearQaHandle"
      >
        <Eraser class="w-3.5 h-3.5" />
      </button>
    </div>
  </div>

  <div class="mt-1.5 space-y-2">
    <div class="p-2 space-y-2 rounded-md bg-muted/50 highlight-white/5">
      <div
        spellcheck="false"
        autocorrect="off"
        autocapitalize="off"
        writingsuggestions="false"
        translate="no"
        contenteditable="true"
        role="textbox"
      >
        <p class="font-mono text-sm font-semibold text-indigo-400">
          Q:<span>{{ questionData.title }}</span>
        </p>
        <div class="font-mono text-xs text-indigo-400 text-neutral-300 my-0.5">
          <ul class="flex">
            <li
              v-for="(item, index) in questionData.answers"
              :key="index + item"
              class="px-1"
            >
              <UiCodemirror
                :key="editorKey"
                :extensions="[html(), EditorView.lineWrapping]"
                :model-value="item"
                :theme-options="{
                  settings: {
                    background: 'transparent',
                    gutterBackground: 'transparent',
                  },
                }"
                placeholder="HTML here"
                class="p-2 text-sm"
              />
            </li>
          </ul>
        </div>
      </div>
    </div>
  </div>

  <section class="mt-4">
    <div class="flex items-center justify-between">
      <p class="font-semibold">聊天</p>
      <div>
        <button
          class="inline-flex items-center h-8 px-3 text-sm transition rounded-sm bg-secondary highlight-white/5 text-secondary-foreground hover:bg-secondary/80"
          :disabled="loading"
          spellcheck="false"
          autocorrect="off"
          autocapitalize="off"
          writingsuggestions="false"
          translate="no"
          contenteditable="true"
          role="textbox"
          @click="sendMessageHandle()"
        >
          <Shell
            v-if="loading"
            class="w-3.5 h-3.5 mr-1 -ml-1"
            :class="{ 'animate-spin': loading }"
          />
          <Send v-else class="w-3.5 h-3.5 mr-1 -ml-1" /> AI
        </button>
        <button
          class="inline-flex items-center h-8 px-3 mx-1 text-sm transition rounded-sm bg-secondary highlight-white/5 text-secondary-foreground hover:bg-secondary/80"
          :disabled="loading"
          @click="sendMessageHandle('你当前的人设是什么?')"
        >
          <Shell
            v-if="loading"
            class="w-3.5 h-3.5"
            :class="{ 'animate-spin': loading }"
          />
          <UserSearch v-else class="w-3.5 h-3.5" />
        </button>
      </div>
    </div>
    <div class="mt-2 rounded-md bg-muted/50 highlight-white/5">
      <UiCodemirror
        :key="editorKey"
        :extensions="[html(), EditorView.lineWrapping]"
        :model-value="innerHTML"
        :theme-options="{
          settings: {
            background: 'transparent',
            gutterBackground: 'transparent',
          },
        }"
        placeholder="HTML here"
        class="p-2 text-sm"
        @change="updateInnerHTML"
      />
    </div>
  </section>

  <section class="mt-4">
    <div class="flex items-center justify-between">
      <p class="font-semibold">结果</p>
      <input v-model="isStream" type="checkbox" @change="streamChange" />
    </div>
    <div class="mt-2 rounded-md bg-muted/50 highlight-white/5">
      <div class="p-2 space-y-2 rounded-md bg-muted/50 highlight-white/5">
        <div
          class="font-mono text-sm text-indigo-400"
          style="
            white-space: pre-wrap;
            outline: none;
            max-height: 250px;
            overflow: auto;
          "
          spellcheck="false"
          autocorrect="off"
          autocapitalize="off"
          writingsuggestions="false"
          translate="no"
          contenteditable="true"
          role="textbox"
        >
          {{ aiResponeData }}
        </div>
      </div>
    </div>
  </section>
  <p class="text-xs text-center pt-1.5">{{ booleanUid }}</p>
</template>
<script setup lang="ts">
import { watch, shallowRef, reactive, ref, onMounted } from 'vue';
import { Send, UserSearch, Eraser, Shell } from 'lucide-vue-next';
import { html } from '@codemirror/lang-html';
import UiCodemirror from '@root/src/pages/components/ui/UiCodemirror.vue';
import { EditorView } from '@codemirror/view';
import { getItem, setItem, generateUUID } from '../../../../../utils/helper';
const props = defineProps<{
  element: any;
  triggertype: string;
  presskey: number;
}>();

const innerHTML = shallowRef('');
const editorKey = shallowRef(0);
const loading = shallowRef(false);
const reportLoading = shallowRef(false);
// 问题内容
const questionData = reactive({
  title: '',
  answers: [],
});

function updateInnerHTML(html: string) {
  innerHTML.value = html;
  // eslint-disable-next-line vue/no-mutating-props
  // props.element.innerHTML = html;
}

const clearQaHandle = async () => {
  questionData.title = '';
  questionData.answers = [];
};

let isStream: any = ref(true);
const streamChange = async () => {
  setItem('isStream', isStream.value);
};

const booleanUid = ref('');
onMounted(async () => {
  chrome.runtime.onMessage.addListener(function (request) {
    if (request.action === 'STREAMANSWER') {
      aiResponeData.value += request.data;
      loading.value = false;
    }
  });

  // 检查是否已经生成过唯一ID
  try {
    let sc: any = await getItem('booleanUid');
    console.log('sc: ', sc);
    booleanUid.value = sc;
    if (!sc) {
      booleanUid.value = generateUUID();
      setItem('booleanUid', booleanUid);
    }
  } catch (error) {
    console.log('error: ', error);
    const booleanUid = generateUUID();
    setItem('booleanUid', booleanUid);
  }
  getItem('isStream').then((result) => {
    isStream.value = result;
  });

  chrome.runtime.sendMessage(
    { action: 'CREATE_CHAT', data: 1 },
    function (response) {
      console.log('response: ', response);
      if (response && response.status) {
        aiResponeData.value = 'AI 正常';
      } else {
        aiResponeData.value = 'AI 异常，请检查网络';
      }
    },
  );
});

let aiRespone = shallowRef({});
const aiResponeData = ref(``);

const sendMessageHandle = async (content?: string) => {
  // console.log('content: ', content);
  aiResponeData.value = '';
  let innerHTMLs = content || innerHTML.value;
  if (!innerHTMLs) return '';
  loading.value = true;
  chrome.runtime.sendMessage(
    { action: 'CREATE_MESSAGE', data: innerHTMLs },
    function (response) {
      console.log('response: ', response);
      editorKey.value += 1;
      if (response.status) {
        aiRespone.value = response.msg;
        aiResponeData.value = response.msg.data;
      } else {
        aiResponeData.value = `ERROR ${response.msg}`;
      }
      loading.value = false;
    },
  );
};

const askMessageHandle = async () => {
  aiResponeData.value = '';
  if (!questionData.title || !questionData.answers.length) return '';
  loading.value = true;
  let reportMessage = `
    问题是：${questionData.title}
    选项是：${questionData.answers.join(',')}
  `;
  chrome.runtime.sendMessage(
    { action: 'CREATE_MESSAGE', data: reportMessage },
    function (response) {
      editorKey.value += 1;
      if (response.status) {
        aiRespone.value = response.msg;
        aiResponeData.value = response.msg.data;
      } else {
        aiResponeData.value = `ERRORf ${response.msg}`;
      }

      loading.value = false;
    },
  );
};

const reportMessageHandle = async () => {
  aiResponeData.value = '';
  if (!questionData.title || !questionData.answers.length) return '';
  loading.value = true;
  let reportMessage = `
    问题是：${questionData.title}
    我的回答是：${questionData.answers.join(',')}

    请记住我的这个回答，当后续有相关的问题时，请结合这个答案进行回答和思考。
  `;
  chrome.runtime.sendMessage(
    { action: 'CREATE_MESSAGE', data: reportMessage },
    function (response) {
      editorKey.value += 1;
      if (response) {
        aiRespone.value = response;
        aiResponeData.value = response.msg.data;
      } else {
        aiResponeData.value = 'ERROR';
      }

      loading.value = false;
    },
  );
};

// eslint-disable-next-line @typescript-eslint/no-explicit-any
const getFormElementValue = (element: any) => {
  if (!element) return;
  if (element.tagName === 'INPUT') {
    // 判断 input 类型（包括 text, radio, checkbox 等）
    if (element.type === 'radio' || element.type === 'checkbox') {
      return element.checked ? element.value : null; // 对于 radio 或 checkbox，返回选中的值
    } else {
      return element.value; // 对于其他类型的 input（如 text），直接返回 value
    }
  } else if (element.tagName === 'SELECT') {
    // 对于 select 元素，获取选中的值
    return element.value;
  } else if (element.tagName === 'TEXTAREA') {
    // 对于 textarea 元素，获取其 value
    return element.value;
  } else {
    return false;
  }
};

watch(
  () => props.element,
  () => {
    let elementInnerHTML = props.element.innerHTML.trim();

    let formFiledValue = getFormElementValue(props.element);
    if (formFiledValue) {
      elementInnerHTML = formFiledValue;
    }

    innerHTML.value = elementInnerHTML;
    editorKey.value += 1;
  },
  { immediate: true },
);

watch(
  () => props.presskey,
  () => {
    let elementInnerTEXT: any = props.element.innerText.trim();

    let formFiledValue = getFormElementValue(props.element);
    if (formFiledValue) {
      elementInnerTEXT = `${formFiledValue}`;
    }

    if (props.triggertype === 'AltLeft') {
      if (elementInnerTEXT) {
        questionData.title = elementInnerTEXT;
      }
    }
    if (props.triggertype === 'Backquote') {
      if (elementInnerTEXT) {
        // 如果 elementInnerTEXT 存在，则删除它
        const index = questionData.answers.indexOf(elementInnerTEXT as never);
        if (index > -1) {
          questionData.answers.splice(index, 1); // 从数组中删除该元素
        } else {
          // 如果 elementInnerTEXT 不存在，则将其添加到数组中
          questionData.answers.push(elementInnerTEXT as never);
        }
      }
    }
  },
);
</script>
